#include "rolemodify.h"
#include "ui_rolemodify.h"
#include <QMessageBox>
#include "msgbox.h"
#include "authmanager.h"
#include "userlogger.h"

RoleModify::RoleModify(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RoleModify)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::setLineEditRoleNameSignal, this, &RoleModify::setLineEditRoleName);
    connect(bdf, &BllDataFlow::updatePermissionListWidgetSignal,this,&RoleModify::updatePermissionListWidget);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &RoleModify::retranslateUiSlot);
    initWidget();
}


RoleModify::~RoleModify()
{
    delete ui;
}

void RoleModify::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void RoleModify::on_btnClose_clicked()
{
    this->hide();
}

void RoleModify::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void RoleModify::setLineEditRoleName(QString name)
{
    ui->lineRoleName->setText(name);
    ui->lineRoleName->setEnabled(false);
}

void RoleModify::updatePermissionListWidget(int permission)
{
    int rowCount = ui->listWidget->count();
    for (int r = 0; r < rowCount; r++)
    {
        if (AuthManager::instance()->hasPermission(permission, (RolePermissionIndex)r))
        {
            ui->listWidget->item(r)->setCheckState(Qt::Checked);
        }
        else
        {
            ui->listWidget->item(r)->setCheckState(Qt::Unchecked);
        }
    }
}

void RoleModify::initWidget()
{
    setAttribute(Qt::WA_TranslucentBackground, true);
//    setShadow({ui->lineRoleName,ui->widget_2});
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget_4->setGraphicsEffect(shadow);
    setWindowFlags(windowFlags() | Qt::SubWindow);
}

void RoleModify::show()
{
    ui->listWidget->scrollToTop();
    QWidget::show();
}

void RoleModify::on_btnConfirmModifyRole_clicked()
{
    QString roleName = ui->lineRoleName->text().trimmed();
    int permission = AuthManager::instance()->basePermission(roleName);
    int count = ui->listWidget->count();
    for (int r = 0; r < count; r++)
    {
        if (ui->listWidget->item(r)->checkState())
        {
            permission = AuthManager::instance()->addPermission(permission, (RolePermissionIndex)r);
        }
        else
        {
            permission = AuthManager::instance()->removePermission(permission, (RolePermissionIndex)r);
        }
    }

    qDebug() << "permission = " << permission;

    //check if role exists
    Role role;
    role.name = roleName;
    QList<Role> info = sqlHelper->selectRoleName(role);
    int roleCount = info.size();
    if(roleCount > 0)
    {
        role = info[0];
    }
    else
    {
        MsgBox::warning(this, tr("Role"), tr("This role not exist"));
        return;
    }

    //check if current permission same as previous permission
    int prevPermission = role.permission;
    if (prevPermission == permission)
    {
        this->hide();
        return;
    }

    role.permission = permission;
    EttaError ret = sqlHelper->updateRole(role);
    if (ret == EttaError::OK)
    {
        QString beforePermissionStr = QString("%1 %2:").arg(tr("Before Modify")).arg(tr("permission"));
        QString afterPermissionStr = QString("%1 %2:").arg(tr("After Modify")).arg(tr("permission"));
        QString message = QString("%1: %2").arg(tr("Modify Role")).arg(role.name);
        for (int r = 0; r < ui->listWidget->count(); r++)
        {// 修改前
            if (AuthManager::instance()->hasPermission(prevPermission, (RolePermissionIndex)r))
            {
                beforePermissionStr += " ";
                beforePermissionStr += ui->listWidget->item(r)->text();
            }
        }

        for (int r = 0; r < ui->listWidget->count(); r++)
        {// 修改后
            if (AuthManager::instance()->hasPermission(permission, (RolePermissionIndex)r))
            {
                afterPermissionStr += " ";
                afterPermissionStr += ui->listWidget->item(r)->text();
            }
        }

        UserLogger::log(QString("%1\n>%2\n>%3").arg(message).arg(beforePermissionStr).arg(afterPermissionStr));
        bdf->showAllRoles();
        this->hide();
    }
    else
    {
        UserLogger::error(QString(tr("Failed to Modify Role %1")).arg(role.name));
        QString result = (ret == EttaError::OK) ? tr("Success") : tr("Failed");
        MsgBox::information(this, tr("Modify Role"), QString(tr("%1 to Modify Role")).arg(result));
    }
}

void RoleModify::on_btnCancelModifyRole_clicked()
{
    this->hide();
}
